"""
@Project:workflow_python
@File:views_management.py
@Author:袁浩天
@Date:18:35
"""
# explain 执行计划 峰值理论

from utils.redis import redis_conn
from users.models import *
from utils.token_utils import login_token
from .serializers import *

from rest_framework.views import APIView
from rest_framework.viewsets import ViewSet
from rest_framework.response import Response
from rest_framework import status

from django.http import HttpResponse
from django.db.models import Q
from django.db.models import F

import string
import random
import json

from utils.token_utils import check_token

# 菜单管理
class MenusView(ViewSet):

    def all_menu(self, request):
        try:
            # 获取前端数据token
            token2 = request.META.get("HTTP_AUTHORIZATION")
            print("token2>>>>>>>>>>>>>>>>>>>>>>>>>", token2)
            payload = check_token(token2)
            # print("payload>>>>>>>>>>>>>>>>>",payload)
            # print(payload.get("id"))
            # request.session["id"] = payload.get("id")
            # print("setting", request.session.get("id"))
            id = payload.get("id")
            print("id>>>>>>>>>>>>>>", id)
            # id = request.session.get("id")
            user = UserModel.objects.get(id=id)
            print(user.rank_id)
            rank = user.rank_id
            # menus = MenuModel.objects.filter(menu_id=None, is_delete=0).all()
            # menus_ser = MenuSer(menus,many=True).data
            data = []
            if rank < 6:
                rank = 5
                menus = MenuModel.objects.filter(menu_id=None, is_delete=0, position=rank)
                print("12")
            if rank > 5 and rank < 14:
                rmenus = MenuModel.objects.filter(menu_id=None, is_delete=0).all()
                print("23")
            if rank > 5 and rank >13:
                menus = MenuModel.objects.filter(menu_id=None, is_delete=0).all()
                print("34")
            print("menus", menus)
            menus_ser = MenuSer(menus,many=True).data
            print(menus_ser)
            for i in menus_ser:
                # 获取父级下的所有子级
                menus2 = MenuModel.objects.filter(menu_id=i['id'], position=rank).all()
                menus2_ser = MenuSer(menus2,many=True).data
                i['menu_data'] = menus2_ser
                data.append(i)
            return Response({'msg': '获取成功','code': status.HTTP_200_OK,'data': data})
        except Exception as e:
            print("获取全部菜单报错", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg":'服务器错误'})

    def add_menu(self, request):
        try:
            menutype = request.data.get("menutype")
            name = request.data.get("name")
            menurl = request.data.get("menurl")
            menuimg = request.data.get("menuimg")
            remark = request.data.get("remark")
            print(request.data)

            menu = MenuModel.objects.filter(name=name, is_delete=0).count()
            if menu != 0:
                return Response({"code":status.HTTP_400_BAD_REQUEST, "msg":'名字已存在'})
            data = {
                "name": name,
                "menutype":menutype,
                "menurl": menurl,
                "menuimg": menuimg,
                "remark": remark
            }
            ser = MenuSer(data=data)
            if not ser.is_valid():
                return Response({"code": status.HTTP_400_BAD_REQUEST,"msg": ser.errors})
            if menutype == "目录":
                MenuModel.objects.create(name=name, menurl=menurl,menuimg=menuimg, remark=remark)
            else:
                menutype = 1
                MenuModel.objects.create(name=name, menurl=menurl,menuimg=menuimg, remark=remark, menu_id=menutype)
            return Response({"code": status.HTTP_200_OK, "msg":"添加成功"})
        except Exception as e:
            print("添加失败", e)
            return Response({"code":status.HTTP_500_INTERNAL_SERVER_ERROR, "msg":"服务器错误"})


# 菜单管理tow
class MenusViewTow(ViewSet):

    # 获取单个
    def one_menu(self, request, id):
        try:
            menus = MenuModel.objects.filter(id=id, is_delete=0).all()
            menus_ser = MenuSer(menus,many=True).data
            # data = []
            # for i in menus_ser:
            #     # 获取父级下的所有子级
            #     menus2 = MenuModel.objects.filter(menu_id=i['id']).all()
            #     menus2_ser = MenuSer(menus2,many=True).data
            #     i['menu_data'] = menus2_ser
            #     data.append(i)
            return Response({'msg': '获取成功','code': status.HTTP_200_OK,'data': menus_ser})
        except Exception as e:
            print("获取全部菜单报错", e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg":'服务器错误'})

    # 修改
    def upd_menu(self, request, id):
        try:
            menutype = request.data.get("menutype")
            name = request.data.get("name")
            menurl = request.data.get("menurl")
            menuimg = request.data.get("menuimg")
            remark = request.data.get("remark")
            print(request.data)

            menu = MenuModel.objects.filter(name=name).count()
            data = {
                "name": name,
                "menutype":menutype,
                "menurl": menurl,
                "menuimg": menuimg,
                "remark": remark
            }
            if name != None:
                data["name"] = name
            if menurl != None:
                data["menurl"] = menurl
            if menutype != None:
                data["menutype"] = menutype
            if menuimg != None:
                data["menuimg"] = menuimg
            if remark != None:
                data["remark"] = remark
            ser = MenuSer(data=data)
            if not ser.is_valid():
                return Response({"code": status.HTTP_400_BAD_REQUEST,"msg": ser.errors})
            if menutype == "目录":
                MenuModel.objects.filter(id=id).update(name=name, menurl=menurl,menuimg=menuimg, remark=remark)
            else:
                menutype = 1
                MenuModel.objects.filter(id=id).update(name=name, menurl=menurl,menuimg=menuimg, remark=remark, menu_id=menutype)
            return Response({"code": status.HTTP_200_OK, "msg":"修改成功"})
        except Exception as e:
            print("添加失败", e)
            return Response({"code":status.HTTP_500_INTERNAL_SERVER_ERROR, "msg":"服务器错误"})

    # 删除
    def del_menu(self, request, id):
        try:
            menu = MenuModel.objects.filter(id=id)
            menu.update(is_delete=1)
            menu.save()
            return Response({"code": status.HTTP_200_OK, "msg":'删除成功'})
        except Exception as e:
            print("删除", e)
            return Response({"code":status.HTTP_500_INTERNAL_SERVER_ERROR, "msg":"服务器错误"})


# 职级管理
class RanksView(ViewSet):

    def all_rank(self, request):
        try:
            rank = RankModel.objects.filter(is_delete=0)
            rank_ser = RankSer(rank, many=True).data
            return Response({"code": status.HTTP_200_OK, "msg":"获取成功", "data":rank_ser})
        except Exception as e:
            print(e)
            return Response({'code': status.HTTP_500_INTERNAL_SERVER_ERROR, "msg":"服务器错误"})

    def add_rank(self, request):
        try:
            name = request.data.get("rankname")
            remark = request.data.get("rankremark")

            rank = RankModel.objects.filter(name=name).count()

            if rank != 0:
                return Response({"code":status.HTTP_400_BAD_REQUEST, "msg":"该职级已存在"})

            data = {
                "name": name,
                "remark": remark
            }

            ser = RankSer(data=data)
            if not ser.is_valid():
                return Response({"code": status.HTTP_400_BAD_REQUEST,"msg": ser.errors})

            RankModel.objects.create(name=name, remark=remark)
            return Response({"code":status.HTTP_200_OK, "msg":"添加成功"})
        except Exception as e:
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg":"服务器错误"})


# 职级管理tow
class RanksViewTow(ViewSet):

    def one_rank(self, request, pk):
        try:
            rank = RankModel.objects.filter(id=pk, is_delete=0)
            rank_ser = RankSer(rank, many=True).data
            return Response({"code": status.HTTP_200_OK, "msg":"获取成功", "data":rank_ser})
        except Exception as e:
            print(e)
            return Response({'code': status.HTTP_500_INTERNAL_SERVER_ERROR, "msg":"服务器错误"})

    def upd_rank(self, request, pk):
        try:
            name = request.data.get("rankname")
            remark = request.data.get("rankremark")

            rank = RankModel.objects.filter(name=name).count()

            data = {
                "name": name,
                "remark": remark
            }

            ser = RankSer(data=data)
            if not ser.is_valid():
                return Response({"code": status.HTTP_400_BAD_REQUEST,"msg": ser.errors})

            RankModel.objects.filter(id=pk).update(name=name, remark=remark)
            return Response({"code":status.HTTP_200_OK, "msg":"修改"})
        except Exception as e:
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg":"服务器错误"})

    def def_rank(self, request, pk):
        try:
            rank = RankModel.objects.filter(id=pk, is_delete=0)
            rank.update(is_delete=1)
            return Response({"code": status.HTTP_200_OK, "msg":'删除成功'})
        except Exception as e:
            print("删除", e)
            return Response({"code":status.HTTP_500_INTERNAL_SERVER_ERROR, "msg":"服务器错误"})


# 岗位管理
class ManagementsView(ViewSet):

    def get_managements(self, request):
        try:
            position = PositionRoleModel.objects.filter(is_delete=0)
            position_ser = PositionRoleSer(position, many=True).data
            return Response({"code": status.HTTP_200_OK, "msg":"获取成功", "data":position_ser})
        except Exception as e:
            print(e)
            return Response({'code': status.HTTP_500_INTERNAL_SERVER_ERROR, "msg":"服务器错误"})

    def add_managements(self, request):
        try:
            name = request.data.get("mentname")
            remark = request.data.get("mentremark")
            ranks = request.data.get("rank")
            print(request.data.get("rank"))

            position = PositionModel.objects.filter(name=name, is_delete=0).count()

            if position != 0:
                return Response({"code": status.HTTP_400_BAD_REQUEST,"msg": "该岗位已存在"})

            data = {
                "name": name,
                "remark": remark,
                "rank": ranks,
                "department": 2
            }

            ser = PositionSerTow(data=data)
            if not ser.is_valid():
                return Response({"code": status.HTTP_400_BAD_REQUEST,"msg": ser.errors})
            PositionModel.objects.create(name=name, rank_id=ranks, department_id=2)
            return Response({"code": status.HTTP_200_OK,"msg": "添加成功"})
        except Exception as e:
            print(e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR,"msg": "服务器错误"})


# 岗位管理2
class ManagementsViewTow(ViewSet):

    def one_managements(self, request, pk):
        try:
            position = PositionRoleModel.objects.filter(id=pk, is_delete=0)
            position_ser = PositionRoleSer(position, many=True).data
            return Response({"code": status.HTTP_200_OK, "msg":"获取成功", "data":position_ser})
        except Exception as e:
            print(e)
            return Response({'code': status.HTTP_500_INTERNAL_SERVER_ERROR, "msg":"服务器错误"})

    def upd_managements(self, request, pk):
        try:
            name = request.data.get("mentname")
            remark = request.data.get("mentremark")
            ranks = request.data.get("rank")
            print(request.data.get("rank"))

            position = PositionModel.objects.filter(name=name, is_delete=0).count()

            if position != 0:
                return Response({"code": status.HTTP_400_BAD_REQUEST,"msg": "该岗位已存在"})

            data = {
                "name": name,
                "remark": remark,
                "rank": ranks,
                "department": 2
            }

            ser = PositionSerTow(data=data)
            if not ser.is_valid():
                return Response({"code": status.HTTP_400_BAD_REQUEST,"msg": ser.errors})
            PositionModel.objects.filter(id=pk).update(name=name,rank_id=ranks,department_id=2)
            return Response({"code": status.HTTP_200_OK,"msg": "修改成功"})
        except Exception as e:
            print(e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR,"msg": "服务器错误"})

    def del_managements(self, request, pk):
        try:
            position = PositionModel.objects.filter(id=pk).update(is_delete=1)
            return Response({"code": status.HTTP_200_OK, "msg":'删除成功'})
        except Exception as e:
            print("删除", e)
            return Response({"code":status.HTTP_500_INTERNAL_SERVER_ERROR, "msg":"服务器错误"})


# 部门管理
class DepartmentView(ViewSet):

    def get_department(self, request):
        try:
            department = DepartmentModel.objects.filter(is_delete=0)
            department_ser = DepartmentSer(department, many=True).data
            data = []
            for i in department_ser:
                # 获取父级下的所有子级
                department2 = DepartmentModel.objects.filter(level_id=i['id'], is_delete=0).all()
                department2_ser = DepartmentSer(department2,many=True).data
                i['department'] = department2_ser
                data.append(i)
            return Response({"code": status.HTTP_200_OK, "msg":"获取成功", "data":department_ser})
        except Exception as e:
            print(e)
            return Response({'code': status.HTTP_500_INTERNAL_SERVER_ERROR, "msg":"服务器错误"})

    def add_department(self, request):
        try:
            name = request.data.get("name")
            remark = request.data.get("remark")
            level = request.data.get("level")
            print(request.data)

            department = DepartmentModel.objects.filter(name=name).count()

            if department != 0:
                return Response({"code": status.HTTP_400_BAD_REQUEST,"msg": "该部门已存在"})

            levels = DepartmentModel.objects.all()
            levels_ser = DepartmentSer(levels, many=True).data
            print(levels_ser)

            for level_name in levels_ser:
                print(level_name.get("name"))
                if level_name.get("name") == level:
                    level = level_name.get("id")

            data = {
                "name": name,
                "remark": remark,
                "level":level
            }

            ser = DepartmentSer(data=data)
            if not ser.is_valid():
                return Response({"code": status.HTTP_400_BAD_REQUEST,"msg": ser.errors})
            DepartmentModel.objects.create(name=name, level_id=level, remark=remark)
            return Response({"code": status.HTTP_200_OK,"msg": "添加成功"})
        except Exception as e:
            print(e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR,"msg": "服务器错误"})


# 部门管理2
class DepartmentViewTow(ViewSet):

    def one_department(self, request, pk):
        try:
            department = DepartmentModel.objects.filter(id=pk,is_delete=0)
            department_ser = DepartmentSer(department, many=True).data
            return Response({"code": status.HTTP_200_OK, "msg":"获取成功", "data":department_ser})
        except Exception as e:
            print(e)
            return Response({'code': status.HTTP_500_INTERNAL_SERVER_ERROR, "msg":"服务器错误"})

    def upd_department(self, request, pk):
        try:
            name = request.data.get("name")
            remark = request.data.get("remark")
            level = request.data.get("level")
            print(request.data)

            department = DepartmentModel.objects.filter(name=name, is_delete=0).count()

            levels = DepartmentModel.objects.all()
            levels_ser = DepartmentSer(levels, many=True).data
            print(levels_ser)

            for level_name in levels_ser:
                print(level_name.get("name"))
                if level_name.get("name") == level:
                    level = level_name.get("id")

            data = {
                "name": name,
                "remark": remark,
                "level":level
            }

            ser = DepartmentSer(data=data)
            if not ser.is_valid():
                return Response({"code": status.HTTP_400_BAD_REQUEST,"msg": ser.errors})
            DepartmentModel.objects.filter(id=pk).update(name=name, level_id=level, remark=remark)
            return Response({"code": status.HTTP_200_OK,"msg": "修改成功"})
        except Exception as e:
            print(e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR,"msg": "服务器错误"})

    def del_department(self, request, pk):
        try:
            DepartmentModel.objects.filter(id=pk).update(is_delete=1)
            return Response({"code": status.HTTP_200_OK, "msg":'删除成功'})
        except Exception as e:
            print("删除", e)
            return Response({"code":status.HTTP_500_INTERNAL_SERVER_ERROR, "msg":"服务器错误"})


# 角色管理
class RolesViews(ViewSet):

    def get_role(self, request):
        try:
            role = RoleModel.objects.filter(is_delete=0)
            role_ser = RoleSer(role, many=True).data
            return Response({"code": status.HTTP_200_OK, "msg":"获取成功", "data":role_ser})
        except Exception as e:
            print(e)
            return Response({'code': status.HTTP_500_INTERNAL_SERVER_ERROR, "msg":"服务器错误"})

    def add_role(self, request):
        try:
            name = request.data.get("rolename")
            remark = request.data.get("remark")
            permission = request.data.get("permission")
            print(request.data)

            data = {
                "rolename": name,
                "remark": remark,
            }
            ser = RoleSer(data=data)
            if not ser.is_valid():
                return Response({"code": status.HTTP_400_BAD_REQUEST,"msg": ser.errors})

            role = RoleModel.objects.filter(rolename=name)

            if role:
                role_ser = RoleSer(role,many=True).data
            else:
                # 添加并查询角色
                RoleModel.objects.create(rolename=name,remark=remark)
                role = RoleModel.objects.filter(rolename=name)
                role_ser = RoleSer(role,many=True).data

            for role in role_ser:
                print(role_ser)
                if role.get("rolename") == name:
                    name = role.get("id")

            # 查询权限数据
            permissions = PermissionModel.objects.all()
            permission_ser = PermissionSer(permissions, many=True).data
            # 循环角色并判断与传递的名字相同的角色

            for permissions in permission_ser:
                if permissions.get("permission_name") == permission:
                    # print("角色id（现在）",name)
                    permissiones = PermissionModel.objects.filter(permission_name=permission, role_id=name).count()
                    if permissiones == 0:
                        PermissionModel.objects.create(role_id=name, permission_name=permission, path=permission)
            return Response({"code": status.HTTP_200_OK,"msg": "添加成功"})
        except Exception as e:
            print(e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR,"msg": "服务器错误"})


# 角色管理2
class RolesViewsTow(ViewSet):

    def one_role(self, request, pk):
        try:
            role = RoleModel.objects.filter(id=pk, is_delete=0)
            role_ser = RoleSer(role, many=True).data
            return Response({"code": status.HTTP_200_OK, "msg":"获取成功", "data":role_ser})
        except Exception as e:
            print(e)
            return Response({'code': status.HTTP_500_INTERNAL_SERVER_ERROR, "msg":"服务器错误"})

    def upd_role(self, request, pk):
        try:
            name = request.data.get("rolename")
            remark = request.data.get("remark")
            permission = request.data.get("permission")
            print(request.data)

            data = {
                "rolename": name,
                "remark": remark,
            }
            ser = RoleSer(data=data)
            if not ser.is_valid():
                return Response({"code": status.HTTP_400_BAD_REQUEST,"msg": ser.errors})

            role = RoleModel.objects.filter(rolename=name)

            if role:
                role_ser = RoleSer(role,many=True).data
            else:
                # 修改并查询角色
                RoleModel.objects.filter(id=pk).update(rolename=name,remark=remark)
                role = RoleModel.objects.filter(rolename=name)
                role_ser = RoleSer(role,many=True).data

            for role in role_ser:
                print(role_ser)
                if role.get("rolename") == name:
                    name = role.get("id")

            # 查询权限数据
            permissions = PermissionModel.objects.all()
            permission_ser = PermissionSer(permissions, many=True).data
            # 循环角色并判断与传递的名字相同的角色

            for permissions in permission_ser:
                if permissions.get("permission_name") != permission:
                    # print("角色id（现在）",name)
                    permissiones = PermissionModel.objects.create(role_id=name,permission_name=permission)
            return Response({"code": status.HTTP_200_OK,"msg": "修改成功"})
        except Exception as e:
            print(e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR,"msg": "服务器错误"})

    def del_role(self, request, pk):
        try:
            RoleModel.objects.filter(id=pk).update(is_delete=1)
            return Response({"code": status.HTTP_200_OK, "msg":'删除成功'})
        except Exception as e:
            print("删除", e)
            return Response({"code":status.HTTP_500_INTERNAL_SERVER_ERROR, "msg":"服务器错误"})






















